package com.skyline.user.controller;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.skyline.base.controller.BaseController;
import com.skyline.base.type.IdolType;
import com.skyline.common.util.AuthorityUtil;
import com.skyline.common.util.Constant;
import com.skyline.common.util.ViewPaths;
import com.skyline.common.util.WebHelper;
import com.skyline.user.model.Fan;
import com.skyline.user.model.User;
import com.skyline.user.service.AttentionService;
import com.skyline.user.service.BasicUserService;

/**
 * BasicUserAction 用户基本操作，NameSpace为"/" 功能包括: 1.登陆 2.退出 3.注册
 * 
 * @author Jairus Chan
 * @version 0.1, 11/30/10
 */

@Controller
public class BasicUserController extends BaseController {
	private static final Log LOGGER = LogFactory.getLog(BasicUserController.class);

	@Autowired
	private BasicUserService basicUserService;

	@Autowired
	private AttentionService attentionService;

	// @Autowired
	// private AuthorityUtil authorityUtil;

	// /** /base/login */
	// private @Value("${view.user.login}")
	// String loginView;
	//
	// // /** /base/logined */
	// // private @Value("${view.user.logined}")
	// // String loginedView;
	//
	// /** /base/regist */
	// private @Value("${view.user.regist}")
	// String registView;
	//
	// private @Value("${view.wo.myWo}")
	// String myWoView;

	/**
	 * loginRequest() 用户访问"/login.html"跳转到登陆界面
	 */
	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public ModelAndView loginRequest(String requestFrom) {
		ModelAndView v = new ModelAndView();
		v.setViewName(ViewPaths.USER_LOGIN);
		v.addObject("REQUEST_FROM", StringUtils.trimToEmpty(requestFrom));
		WebHelper.saveToken(null);
		return v;
	}

	/**
	 * loginExecute() 对用户输入的信息进行验证，施行登陆
	 */
	// FIXME 不要返回String
	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public String loginExecute(String email, String password, String requestFrom) {
		String loginIp = WebHelper.initRequest(null).getRemoteAddr();
		User user = basicUserService.login(email, password, loginIp);
		WebHelper.initRequest(null).setAttribute("REQUEST_FROM",
				StringUtils.trimToEmpty(requestFrom));
		if (user != null) {
			List<Fan> idols = attentionService.queryAttentionByType(user.getId(), IdolType.USER);
			AuthorityUtil.initalAuthorityMatrix(null, user.getId(), idols);
			WebHelper.setSessionAttribute(null, Constant.SESSION_USER, user);
			WebHelper.setSessionAttribute(null, Constant.SESSION_IDOLS, idols);
			LOGGER.debug("登录成功，目标地址："+requestFrom);
			if (StringUtils.isEmpty(requestFrom)) {
				// return loginedView;
				// 当登录成功后，跳转到myWo页面
				return "redirect:" + ViewPaths.WO_MYWO + URL_SUFFIX;
			} else {
				return "redirect:" + requestFrom;
			}
		} else {
			return ViewPaths.USER_LOGIN;
		}
	}

	/**
	 * logout（） 退出，结束session
	 */
	@RequestMapping("/logout")
	public ModelAndView logout() {
		WebHelper.invalidateSession(null);
		ModelAndView v = new ModelAndView();
		v.setViewName(ViewPaths.USER_LOGIN);
		return v;
	}

	/**
	 * registRequest() 请求注册，当用户输入“/regist.html”时，跳转到注册界面
	 */
	@RequestMapping(value = "/regist", method = RequestMethod.GET)
	public ModelAndView registRequest() {
		ModelAndView v = new ModelAndView();
		v.setViewName(ViewPaths.USER_REGIST);
		return v;
	}

	/**
	 * registExecute（） 执行注册
	 */
	@RequestMapping(value = "/regist", method = RequestMethod.POST)
	public ModelAndView registExecute(String email, String password, String passwordConfirm,
			String certcode) {
		ModelAndView v = new ModelAndView();
		String ip = WebHelper.initRequest(null).getRemoteAddr();
		String certcodeInSession = (String) WebHelper.getSessionAttribute(null,
				Constant.SESSION_CERT_CODE);
		if (certcode == null || !certcode.equals(certcodeInSession)) {
			v.setViewName(ViewPaths.USER_REGIST);
			return v;
		}
		if (email == null) {
			v.setViewName(ViewPaths.USER_REGIST);
			return v;
		} else if (password == null || !password.equals(passwordConfirm)) {
			v.setViewName(ViewPaths.USER_REGIST);
			return v;
		}
		try {
			basicUserService.regist(email, password, ip);
			v.setViewName(ViewPaths.USER_LOGIN);
			return v;
		} catch (Exception e) {
			e.printStackTrace();
			v.setViewName(ViewPaths.USER_REGIST);
			v.addObject("email", email);
			return v;
		}
	}

	/**
	 * verifyUser（） 这是一个Ajax请求，验证此用户是否已经存在
	 */
	@RequestMapping("/verifyuser/{email}")
	@ResponseBody
	public Boolean verifyUser(@PathVariable String email) {
		return basicUserService.isUserExist(email);
	}

	/**
	 * ajaxLogin（） 这是一个Ajax请求，通过ajax登陆系统
	 */
	@RequestMapping("/ajaxlogin")
	@ResponseBody
	public boolean ajaxLogin(String email, String password) {
		String loginIp = WebHelper.initRequest(null).getRemoteAddr();
		// logger.debug(email + ":::" + password);
		User user = basicUserService.login(email, password, loginIp);
		WebHelper.saveToken(null);
		if (user != null) {
			List<Fan> idols = attentionService.queryAttentionByType(user.getId(), IdolType.USER);
			AuthorityUtil.initalAuthorityMatrix(null, user.getId(), idols);
			WebHelper.setSessionAttribute(null, Constant.SESSION_USER, user);
			WebHelper.setSessionAttribute(null, Constant.SESSION_IDOLS, idols);
			return true;
		} else {
			return false;
		}
	}

	@RequestMapping("/getlogineduser")
	@ResponseBody
	public User getLoginedUser() {
		User user = (User) WebHelper.getSessionAttribute(null, Constant.SESSION_USER);
		if (user == null) {
			user = new User();
			user.setId(Long.valueOf(0));
			user.setNickname("游客");
			user.setPortrait("portrait");
		}
		// u.getPortrait()
		return user;
	}
}
